目標網站:https://www.tpex.org.tw/
進入網站後點選上櫃/盤後資訊/個股日成交資訊
以下是我填選111/09月份、股票代號5820日盛金的盤後資訊。
點選另存CSV檔案就可以下載並用EXCEL開啟。
因為今天要繪圖所以要import一些東西
import csv
import matplotlib.pyplot as plt
from datetime import datetime
由於這個表格的前面5行是股票的基本資訊最、最後一行是筆數,我們可以將其轉成串列後利用切片刪除前5行和最後一行:
listCsv = list(csvReader)
csvData = listCsv[5:-1]
接下來是設定跟儲存想要的值:
dates, highs, lows, prices = [], [], [], []
for row in csvData:
try:
datestr = row[0].replace('111', '2022')
currentDate = datetime.strptime(datestr, '%Y-%m-%d')
high = float(row[4])
low = float(row[5])
price = float(row[6])
except Exception:
print('有缺值')
else:
highs.append(high)
lows.append(low)
prices.append(price)
dates.append(currentDate)
接下來就是繪圖:
fig = plt.figure(dpi=80, figsize=(12, 8))
plt.plot(dates, highs, '_*', label = 'HIGH')
plt.plot(dates, lows, '-o', label = 'LOW')
plt.plot(dates, prices, '-^', label = 'PRICE')
plt.legend(loc = 'best')
fig.autofmt_xdate()
plt.title('STOCK 5820, September 2022', fontsize = 25)
plt.xlabel('', fontsize = 15)
plt.ylabel('Price', fontsize = 15)
plt.tick_params(axis='both', labelsize = 12, color = 'blue')
plt.show()
打完程式碼後發現執行失敗…找不到csv檔案:
FileNotFoundError: [Errno 2] No such file or directory: 'ST43_5820_202209.csv'
我會再試試看後再上來更新。
解決找不到路徑的問題了,但是繪圖會不出來......
import csv
import matplotlib.pyplot as plt
from datetime import datetime
fn = '/Users/sunwei/Desktop/iThone/Day21/ST43_5820_202209.csv'
with open(fn) as csvFile:
csvReader = csv.reader(csvFile)
listCsv = list(csvReader)
csvData = listCsv[5:-1]
dates, highs, lows, prices = [], [], [], []
for row in csvData:
try:
datestr = row[0].replace('111', '2022')
currentDate = datetime.strptime(datestr, '%Y-%m-%d')
high = float(row[4])
low = float(row[5])
price = float(row[6])
except Exception:
print('有缺值')
else:
highs.append(high)
lows.append(low)
prices.append(price)
dates.append(currentDate)
fig = plt.figure(dpi=80, figsize=(12, 8))
plt.plot(dates, highs, '-*', label = 'HIGH')
plt.plot(dates, lows, '-o', label = 'LOW')
plt.plot(dates, prices, '-^', label = 'PRICE')
plt.legend(loc = 'best')
fig.autofmt_xdate()
plt.title('STOCK 5820, September 2022', fontsize = 25)
plt.xlabel("", fontsize = 15)
plt.ylabel('Price', fontsize = 15)
plt.tick_params(axis='both', labelsize = 12, color = 'red')
plt.show()
參考書籍:
洪錦魁 -- Python網路爬蟲:大數據擷取、清洗、儲存與分析:王者歸來 2019
林俊瑋, 林修博 --- Python:網路爬蟲與資料分析入門實戰 2018